<script setup>
import {
  ref,
  computed,
  onMounted,
  onBeforeUnmount,
  nextTick,
  useTemplateRef,
} from "vue";
import {
  Menu,
  Refresh,
  Scissor,
  Fold,
  ChatDotSquare,
  Back,
  MoreFilled,
  Edit,
  Download,
} from "@element-plus/icons-vue";
import ShortcutDialog from "./ShortcutDialog.vue";
import TourGuide from "./TourGuide.vue";
import DownloadProgress from "./DownloadProgress.vue";

const props = defineProps({ webview: Object | null });
const emit = defineEmits([
  "toggleChatroom",
  "refresh",
  "back",
  "openIssueDrawer",
]);
const defaultWH = 52;
const isExpanded = ref(false);
const dockSide = ref("right");
const boxTop = ref(0);
const boxLeft = ref(0);
const isDragging = ref(false);
const transitionStyle = ref("left 0.3s, top 0.3s, width 0.3s");
let dragOffsetY = 0,
  dragOffsetX = 0,
  rafId = null,
  lastY = 0,
  lastX = 0;
const shortcutDialogRef = ref();
const downloadProgressRef = ref();
const showDownloadProgress = ref(false);
const tourguideRef = ref(null);

const boxHeight = defaultWH;
const boxWidth = computed(() =>
  isExpanded.value ? defaultWH * tools.length + 10 : defaultWH
);

const mainBtnRef = useTemplateRef();
const toolBtnRefs = useTemplateRef({});

const tools = [
  {
    icon: Scissor,
    key: "screenshot",
    label: "截图",
    hotKey: "Ctrl+1",
    onClick: () => window.electronAPI?.sendToScreenHandle?.(),
  },
  {
    icon: ChatDotSquare,
    key: "chatroom",
    label: "聊天室",
    hotKey: "Ctrl+2",
    onClick: () => emit("toggleChatroom"),
  },
  {
    icon: Refresh,
    key: "refresh",
    label: "刷新",
    hotKey: "F5",
    onClick: () => emit("refresh"),
  },
  { icon: Back, key: "back", label: "返回", onClick: () => emit("back") },
  {
    icon: Edit,
    key: "issue",
    label: "问题反馈",
    onClick: () => emit("openIssueDrawer"),
  },
  {
    icon: Download,
    key: "downloads",
    label: "下载管理",
    onClick: () => (showDownloadProgress.value = true),
  },
  {
    icon: MoreFilled,
    key: "all",
    label: "查看全部",
    onClick: () => (shortcutDialogRef.value.visible = true),
  },
];

// Tour 步骤
const tourItems = [
  ...tools.map((tool, idx) => {
    let desc = "";
    switch (tool.key) {
      case "screenshot":
        desc = `点击此按钮${
          tool.hotKey ? "或使用快捷键" + tool.hotKey : ""
        }可以${tool.label.split("(")[0]}`;
        break;
      case "chatroom":
        desc = `点击此按钮${
          tool.hotKey ? "或使用快捷键" + tool.hotKey : ""
        }可以打开/关闭聊天室`;
        break;
      case "refresh":
        desc = `点击此按钮${
          tool.hotKey ? "或使用快捷键" + tool.hotKey : ""
        }可以刷新当前页面`;
        break;
      case "back":
        desc = "点击此按钮可以返回上一页";
        break;
      case "downloads":
        desc = "点击此按钮可以查看下载进度和历史记录";
        break;
      case "all":
        desc = "点击此按钮可以查看所有快捷键操作";
        break;
      case "issue":
        desc = "点击此按钮可以去反馈遇到的问题及需求";
        break;
      default:
        break;
    }
    return {
      title: tool.label,
      description: desc,
      placement: "bottom",
      target: `.toolitem_${idx}`,
    };
  }),
  {
    target: () => mainBtnRef.value?.$el || mainBtnRef.value,
    title: "收起工具箱",
    description: "点击此按钮收起工具箱",
    placement: "bottom",
  },
];

function setDefaultPosition() {
  const cache = localStorage.getItem("toolbox-position");
  if (cache) {
    try {
      const { boxTop: cachedTop, dockSide: cachedDock } = JSON.parse(cache);
      boxTop.value = Math.max(
        0,
        Math.min(window.innerHeight - boxHeight, cachedTop)
      );
      dockSide.value = cachedDock === "right" ? "right" : "left";
      nextTick(() => {
        boxLeft.value =
          dockSide.value === "right" ? window.innerWidth - boxWidth.value : 0;
      });
    } catch (e) {
      boxTop.value = 100;
      dockSide.value = "right";
      nextTick(() => {
        boxLeft.value = window.innerWidth - boxWidth.value;
      });
    }
  } else {
    boxTop.value = 100;
    dockSide.value = "right";
    nextTick(() => {
      boxLeft.value = window.innerWidth - boxWidth.value;
    });
  }
}
function startDrag(e) {
  isDragging.value = true;
  transitionStyle.value = "none";
  dragOffsetY = e.clientY - boxTop.value;
  dragOffsetX = e.clientX - boxLeft.value;
  lastY = boxTop.value;
  lastX = boxLeft.value;
  document.body.style.userSelect = "none";
  window.addEventListener("mousemove", onDrag);
  window.addEventListener("mouseup", stopDrag);
}
function onDrag(e) {
  if (!isDragging.value) return;
  let newTop = e.clientY - dragOffsetY;
  let newLeft = e.clientX - dragOffsetX;
  newTop = Math.max(0, Math.min(window.innerHeight - boxHeight, newTop));
  newLeft = Math.max(0, Math.min(window.innerWidth - boxWidth.value, newLeft));
  if (newTop !== lastY || newLeft !== lastX) {
    lastY = newTop;
    lastX = newLeft;
    if (!rafId) {
      rafId = requestAnimationFrame(() => {
        boxTop.value = lastY;
        boxLeft.value = lastX;
        rafId = null;
      });
    }
  }
}
function stopDrag() {
  isDragging.value = false;
  transitionStyle.value = "left 0.3s, top 0.3s, width 0.3s";
  const centerX = boxLeft.value + boxWidth.value / 2;
  if (centerX < window.innerWidth / 2) {
    dockSide.value = "left";
    boxLeft.value = 0;
  } else {
    dockSide.value = "right";
    boxLeft.value = window.innerWidth - boxWidth.value;
  }
  localStorage.setItem(
    "toolbox-position",
    JSON.stringify({ boxTop: boxTop.value, dockSide: dockSide.value })
  );
  document.body.style.userSelect = "";
  window.removeEventListener("mousemove", onDrag);
  window.removeEventListener("mouseup", stopDrag);
  if (rafId) {
    cancelAnimationFrame(rafId);
    rafId = null;
  }
}
function toggleExpand() {
  isExpanded.value = !isExpanded.value;
  nextTick(() => {
    if (dockSide.value === "right") {
      boxLeft.value = window.innerWidth - boxWidth.value;
    } else {
      boxLeft.value = 0;
    }
  });
}

onMounted(() => {
  setDefaultPosition();
  window.addEventListener("resize", () => {
    if (boxTop.value > window.innerHeight - boxHeight) {
      boxTop.value = window.innerHeight - boxHeight;
    }
    if (dockSide.value === "right") {
      boxLeft.value = window.innerWidth - boxWidth.value;
    } else {
      boxLeft.value = 0;
    }
  });

  // 首次引导
  if (!localStorage.getItem("toolbox-tour-completed")) {
    isExpanded.value = true;
    nextTick(() => tourguideRef.value.open());
  }
});
onBeforeUnmount(() => {
  window.removeEventListener("mousemove", onDrag);
  window.removeEventListener("mouseup", stopDrag);
  if (rafId) cancelAnimationFrame(rafId);
});

// 暴露下载进度组件引用给父组件
defineExpose({
  downloadProgress: downloadProgressRef,
  mainBtnRef,
  toolBtnRefs,
  isExpanded,
});
</script>

<template>
  <div
    :class="[
      'electron-mainapp-toolbox',
      dockSide,
      isExpanded ? 'expanded' : 'non-expand',
    ]"
    :style="{
      top: boxTop + 'px',
      left: boxLeft + 'px',
      width: boxWidth + 'px',
      height: boxHeight + 'px',
      transition: transitionStyle,
      cursor: isDragging ? 'grabbing' : 'grab',
      flexDirection: dockSide === 'right' ? 'row-reverse' : 'row',
      borderRadius: dockSide === 'right' ? '24px 0 0 24px' : '0 24px 24px 0',
    }"
    @mousedown="startDrag"
  >
    <el-tooltip
      :content="isExpanded ? '收起' : '工具箱'"
      placement="top"
      :show-after="500"
    >
      <el-button
        class="futuristic main-btn"
        circle
        :icon="isExpanded ? Fold : Menu"
        type="primary"
        @click.stop="toggleExpand"
        ref="mainBtnRef"
      />
    </el-tooltip>
    <template v-if="isExpanded">
      <template v-for="(tool, idx) in tools" :key="idx">
        <el-tooltip
          :content="tool.hotKey ? tool.label + `(${tool.hotKey})` : tool.label"
          placement="top"
          :show-after="500"
        >
          <el-button
            :class="['futuristic', `toolitem_${idx}`]"
            circle
            :icon="tool.icon"
            @click.stop="tool.onClick"
          />
        </el-tooltip>
      </template>
    </template>
  </div>
  <ShortcutDialog ref="shortcutDialogRef" />
  <TourGuide
    ref="tourguideRef"
    :items="tourItems"
    storageKey="toolbox-tour-completed"
  />
  <DownloadProgress
    ref="downloadProgressRef"
    v-model:visible="showDownloadProgress"
  />
</template>

<style scoped lang="scss">
$defaultWH: 32px;
.electron-mainapp-toolbox {
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 4px 24px 0 rgba(64, 158, 255, 0.08),
    0 1.5px 8px 0 rgba(0, 0, 0, 0.06);
  border: 1.5px solid #f0f4fa;
  display: flex;
  align-items: center;
  user-select: none;
  overflow: hidden;
  position: fixed;
  column-gap: 12px;
  &.non-expand {
    justify-content: center;
  }
  &.expanded {
    &.left {
      .main-btn {
        margin-left: 12px;
      }
    }
    &.right {
      .main-btn {
        margin-right: 12px;
      }
    }
  }

  .futuristic {
    background: #f6faff;
    color: #409eff !important;
    border: 1px solid #b3d8ff;
    box-shadow: 0 2px 8px #b3d8ff22;
    font-size: 16px;
    width: $defaultWH;
    height: $defaultWH;
    min-width: $defaultWH;
    min-height: $defaultWH;
    max-width: $defaultWH;
    max-height: $defaultWH;
    border-radius: 50%;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: box-shadow 0.18s, border 0.18s, background 0.18s,
      transform 0.18s;
    margin: 0;
    .el-icon {
      color: #409eff !important;
      font-size: 16px;
      filter: none;
    }
    &:hover,
    &:focus {
      background: #e3f0ff;
      border: 1.5px solid #409eff;
      box-shadow: 0 0 12px #409eff33;
      color: #1976d2 !important;
      transform: scale(1.07);
      .el-icon {
        color: #1976d2 !important;
      }
    }
  }

  .main-btn {
    background: linear-gradient(135deg, #e3f0ff 0%, #b3e0ff 100%);
    border: 1.5px solid #409eff;
    box-shadow: 0 0 0 3px #e3f0ff;
    color: #1976d2 !important;
    font-weight: bold;
    margin: 0;
  }
}
</style>
